import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
// 导入用户store
import {useUserStore} from '@/stores/user'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView	
    },
    // 管理页面
    {
      path: '/admin',
      name: 'admin',
      meta:{requireAuth:true},
      component: () => import('@/views/admin/AdminView.vue'),
      children:[
        // 管理-概览
        {path:'dash',component:() => import('@/views/admin/DashView.vue') },
        // 管理-商品列表
        {path:'produce/produceList',component:() => import('@/views/admin/produce/ProduceList.vue')},
        // 管理-添加商品
        {path:'produce/addProduce',component:() => import('@/views/admin/produce/AddProduce.vue')},
        // 如果是空重定向到 管理-概览页面
        {path:'',redirect:'/admin/dash'}
      ]
    },
    {
      path: '/about',
      name: 'about',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import('../views/AboutView.vue')
    }
  ]
})
// 实现导航守卫
router.beforeEach((to,from,next)=>{
    const userStore = useUserStore();
    // 如果匹配的路由的第0个里面的meta有equireAuth
    console.log(to.matched,userStore.token)
    if(to.matched[0].meta.requireAuth){
      // 如果pinia有token 放行
      if(userStore.token){
        next()
      }else{
        // 否则就跳转到登录
        next("/")
      }
    }else{
      next();
    }
})
export default router
